package com.creditease.rss.util;

import java.io.IOException;
import java.io.InputStream;

import javax.net.ssl.SSLHandshakeException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
	private final static String TAG = HttpUtils.class.getName();

	public String httptest(String httpUrl) throws IOException {
		HttpGet request = new HttpGet(httpUrl);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpParams params = httpClient.getParams(); // 计算网络超时用.
		String str = "";
		HttpResponse response = httpClient.execute(request);
		// 连接超时
		HttpConnectionParams.setConnectionTimeout(params, 3000);
		// 接收返回数据超时
		HttpConnectionParams.setSoTimeout(params, 5000);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			str = EntityUtils.toString(response.getEntity());
		}

		return str;
	}

	public static InputStream getHttpStream(String httpUrl)
			throws IOException {
		HttpGet request = new HttpGet(httpUrl);
		HttpClient httpClient=HttpConnectionManager.getHttpClient();;
		try {
			HttpResponse response = httpClient.execute(request);	
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				return response.getEntity().getContent();
			}
		}
		catch (IOException e) {
			request.abort();
			throw e;
		}
		return null;
	}

	
	private static DefaultHttpClient httpClient;

	public synchronized static DefaultHttpClient getHttpClient_bak() {

		if(httpClient==null){
			HttpParams params = new BasicHttpParams();
			// 增加最大连接到200
//			ConnManagerParams.setMaxTotalConnections(params, 50);
			/* 连接超时 */
			HttpConnectionParams.setConnectionTimeout(params, 2000);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, 4000);
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, 1000);
			// 增加每个路由的默认最大连接到20
			ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
			// 对localhost:80增加最大连接到50
//			HttpHost localhost = new HttpHost("locahost", 80);
//			connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50);
			ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
			SchemeRegistry schemeRegistry = new SchemeRegistry();
			schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
			ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
			HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
				@Override
				public boolean retryRequest(IOException exception,
											int executionCount,
											HttpContext context) {
					if (executionCount >= 3) {
						// Do not retry if over max retry count
						return false;
					}
					if (exception instanceof NoHttpResponseException) {
						// Retry if the server dropped connection on us
						return true;
					}
					if (exception instanceof SSLHandshakeException) {
						// Do not retry on SSL handshake exception
						return false;
					}
					HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
					boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
					if (idempotent) {
						// Retry if the request is considered idempotent
						return true;
					}
					return false;
				}
			};
			httpClient = new DefaultHttpClient(cm, params);
			httpClient.setHttpRequestRetryHandler(myRetryHandler);
		}
		return httpClient;
	}
	


	public static HttpResponse getHttpHead(String httpUrl)
			throws IOException {
		HttpClient httpClient=HttpConnectionManager.getHttpClient();
		HttpHead request = new HttpHead(httpUrl);
		HttpResponse response = httpClient.execute(request);
		return response;
	}

}
